package cn.edu.xmu.experiment.PulseComms.Service;

import cn.edu.xmu.experiment.PulseComms.entity.GroupChat;
import cn.edu.xmu.experiment.PulseComms.entity.Message;
import cn.edu.xmu.experiment.PulseComms.repository.GroupChatRepository;
import cn.edu.xmu.experiment.PulseComms.repository.MessageRepository;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class GroupService {

    @Autowired
    private GroupChatRepository groupChatRepository;

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public static final String GROUP_EXCHANGE = "group.exchange";

    public GroupChat createGroup(String groupName) {
        GroupChat groupChat = new GroupChat(groupName);
        return groupChatRepository.save(groupChat);
    }

    public boolean joinGroup(String groupName, String username) {
        GroupChat groupChat = groupChatRepository.findByGroupName(groupName);
        if (groupChat != null) {
            groupChat.addMember(username);
            groupChatRepository.save(groupChat);
            return true;
        }
        return false;
    }

    public boolean sendGroupMessage(String groupName, String username, Message message) {
        GroupChat groupChat = groupChatRepository.findByGroupName(groupName);
        if (groupChat != null && groupChat.isMember(username)) {
            message.setGroupName(groupName);
            rabbitTemplate.convertAndSend(GROUP_EXCHANGE, groupName, message);
            messageRepository.save(message);
            return true;
        }
        return false;
    }


}